package com.yidushishizijie;

import java.util.ArrayList;
import java.util.List;

public class ThreadWaitNodifyDemo02 {
    public static void main(String[] args) {
        List list = new ArrayList();
        Thread thread01 = new Thread(new Provider(list),"A");
        Thread thread02 = new Thread(new Consumer(list),"B");
        thread01.start();
        thread02.start();
    }
}


class Provider implements Runnable{   //生产者
    private List list;
    public Provider(List list) {
        this.list = list;
    }
    public void run()  {
        while(true){
            //判断
            synchronized (list){
                if (list.size()>0){
                    try {
                        list.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                //干活
                Object object = new Object();
                list.add(object);
                System.out.println(Thread.currentThread().getName()+"\t"+object);
                //通知
                list.notifyAll();
            }
        }

    }
}

class Consumer implements Runnable{

    private List list;

    public Consumer(List list) {
        this.list = list;
    }
    @Override
    public void run() {
        while(true){
            synchronized (list){
                //判断
                if (list.size()==0){
                    try {
                        list.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                //干活
                Object object = list.remove(0);
                System.out.println(Thread.currentThread().getName()+"\t"+object);
                //通知
                list.notifyAll();
            }
        }
    }
}